package org.asg.dis.controller;

import jakarta.annotation.PostConstruct;
import org.asg.dis.model.Role;
import org.asg.dis.model.Permission;
import org.asg.dis.repository.RoleRepository;
import org.asg.dis.service.ExpressStationService;
import org.asg.dis.service.RbacService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class PreLoader {


    @Autowired
    private RbacService rbacService;
    @Autowired
    private ExpressStationService expressStationService;

    @PostConstruct
    public void loadRolesAndPermissions() {
        List<Role> roles = rbacService.findAll();
        Map<String, Set<String>> rolesPermissions = new HashMap<>();

        for (Role role : roles) {
            Set<String> permissions = role.getPermissions().stream()
                    .map(Permission::getName)
                    .collect(Collectors.toSet());
            rolesPermissions.put(role.getName(), permissions);
        }

        rbacService.cacheRolesAndPermissions(rolesPermissions);
    }

    @PostConstruct
    public void loadExpressStationGeo() {
        // 在应用启动时加载并缓存所有站点的地理位置信息
        expressStationService.cacheGeo();
    }
}
